package http

import (
	"fmt"
	"net/http"

	jsoniter "github.com/json-iterator/go"
)

func GetJson(url string, jsonReq interface{}) ([]byte, error) {
	return GetJsonWithHeaders(url, nil, jsonReq)
}

func PostJson(url string, jsonReq interface{}) ([]byte, error) {
	return PostJsonWithHeaders(url, nil, jsonReq)
}

func GetJsonWithHeaders(url string, headers map[string]string, jsonReq interface{}) ([]byte, error) {

	var err error
	var reqBody []byte

	c := NewClient(url)
	if reqBody, err = jsoniter.Marshal(jsonReq); err != nil {
		return nil, err
	}
	if headers != nil {
		c.Headers = headers
	}
	c.Headers["Content-Type"] = "application/json"
	c.RequestData = reqBody
	if err = c.Get(); err != nil {
		return nil, err
	}

	if c.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("http status code: %d", c.StatusCode)
	}
	return c.ResponseData, err
}

func PostJsonWithHeaders(url string, headers map[string]string, jsonReq interface{}) ([]byte, error) {

	var err error
	var reqBody []byte

	c := NewClient(url)
	if reqBody, err = jsoniter.Marshal(jsonReq); err != nil {
		return nil, err
	}

	if headers != nil {
		c.Headers = headers
	}
	c.Headers["Content-Type"] = "application/json"
	c.RequestData = reqBody
	if err = c.Post(); err != nil {
		return nil, err
	}

	if c.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("http status code: %d", c.StatusCode)
	}
	return c.ResponseData, err
}
